<template>
	<div class="app-container">
		<el-row :gutter="20">
			<!--业务数据-->
			<el-col :span="4" :xs="24">
				<div class="head-container">
					<el-input
						v-model="name"
						:placeholder="$t('calling.businessNameInput')"
						clearable
						size="small"
						prefix-icon="el-icon-search"
						style="margin-bottom: 20px"
					/>
				</div>
				<div class="head-container">
					<el-tree
						ref="tree"
						:data="bizinfoOptions"
						:props="defaultProps"
						:expand-on-click-node="false"
						:filter-node-method="filterNode"
						:highlight-current="true"
						@node-click="handleNodeClick"
					>
						<span class="custom-tree-node" slot-scope="{ node, data }">
							<span>{{ node.label }}</span>
							<span>{{ data.waitNumber || data.awaitNum }}</span>
						</span>
					</el-tree>
				</div>
			</el-col>
			<!--队列数据-->
			<el-col :span="20" :xs="24" style="border-left: 1px solid #f0f0f0;">
				<el-form
					v-show="showSearch"
					ref="queryForm"
					:model="queryParams"
					:inline="true"
				>
					<el-form-item
						:label="$t('calling.ticketNumber')"
						prop="ticketNo"
						size="mini"
					>
						<el-input
							v-model="queryParams.ticketNo"
							:placeholder="$t('calling.ticketNumberInput')"
							clearable
							size="mini"
							@keyup.enter.native="handleQuery"
						/>
					</el-form-item>
					<el-form-item label="患者姓名" prop="customerName" size="mini">
						<el-input
							v-model="queryParams.customerName"
							placeholder="请输入患者姓名"
							clearable
							size="mini"
							@keyup.enter.native="handleQuery"
						/>
					</el-form-item>
          <el-form-item label="患者编号" prop="externalCustomerId" size="mini">
						<el-input
							v-model="queryParams.externalCustomerId"
							placeholder="请输入患者编号"
							clearable
							size="mini"
							@keyup.enter.native="handleQuery"
						/>
					</el-form-item>
					<el-form-item label="就诊医生" prop="staffName" size="mini">
						<el-input
							v-model="queryParams.staffName"
							placeholder="请输入就诊医生"
							clearable
							size="mini"
							@keyup.enter.native="handleQuery"
						/>
					</el-form-item>
					<el-form-item :label="$t('program.status')" prop="status" size="mini">
						<el-select
							v-model="queryParams.status"
							:placeholder="$t('equipment.statusSelect')"
							clearable
							size="mini"
						>
							<el-option
								v-for="dict in statusOptions"
								:key="dict.value"
								:label="dict.label"
								:value="dict.value"
							/>
						</el-select>
					</el-form-item>
					<el-form-item label="报到时间" prop="reportTime" size="mini">
						<el-date-picker
							clearable
							size="mini"
							v-model="reportTime"
							type="datetimerange"
							range-separator="至"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							@change="changeReportTime"
						>
						</el-date-picker>
					</el-form-item>
					<el-form-item size="mini" style="margin:9px 0;padding:0">
						<el-button
							type="primary"
							icon="el-icon-search"
							size="mini"
							@click="handleQuery()"
							>{{ $t('elButton.search') }}
						</el-button>
						<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
							$t('elButton.reset')
						}}</el-button>
					</el-form-item>
				</el-form>

				<el-row :gutter="5" class="mb8">
					<!-- 新增 -->
					<el-col :span="1.5">
						<el-button
							v-hasPerm="['queueInfo_add']"
							type="primary"
							icon="el-icon-plus"
							size="mini"
							@click="handleAdd"
							>{{ $t('elButton.importByhand') }}
						</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-group-button>
							<el-button
								type="success"
								size="mini"
								@click="report"
								:disabled="single"
								>报到
							</el-button>
							<el-button
								type="success"
								size="mini"
								:disabled="single"
								@click="callNum"
								>叫号
							</el-button>
							<el-button
								type="warning"
								size="mini"
								:disabled="single"
								@click="referral"
								>转诊/指诊
							</el-button>
							<el-button
								type="primary"
								size="mini"
								:disabled="single"
								@click="handleEdit"
								v-hasPerm="['queueInfo_edit']"
								icon="el-icon-edit"
								>编辑
							</el-button>
							<el-button
								type="primary"
								size="mini"
								@click="prior"
								:disabled="single"
								>调整优先级
							</el-button>
							<el-button
								type="warning"
								size="mini"
								@click="relisting"
								:disabled="relistingAble"
								>重置入列
							</el-button>
							<el-button
								type="danger"
								size="mini"
								@click="abandoned"
								:disabled="abandonedAble"
								>移出队列
							</el-button>
							<el-button type="success" size="mini" @click="voiceAnnouncements"
								>语音播报
							</el-button>
						</el-group-button>
					</el-col>
					<!-- 快速筛选 -->
					<el-col :span="1.5">
						<el-group-button>
							<span>快速筛选:</span>
							<el-button
								:style="
									status == '0'
										? { background: '#409EFF', color: '#FFF' }
										: { background: '#FFF', color: '#606266' }
								"
								size="mini"
								@click="handleQuickQuery('0')"
								>{{ '待报到' }}
							</el-button>
							<el-button
								v-hasPerm="['queueInfo_add']"
								size="mini"
								:style="
									status == '1'
										? { background: '#409EFF', color: '#FFF' }
										: { background: '#FFF', color: '#606266' }
								"
								@click="handleQuickQuery('1')"
								>{{ '初诊等候' }}
							</el-button>
							<el-button
								:style="
									status == '6'
										? { background: '#409EFF', color: '#FFF' }
										: { background: '#FFF', color: '#606266' }
								"
								size="mini"
								@click="handleQuickQuery('6')"
								>{{ '复诊等候' }}
							</el-button>
							<el-button
								:style="
									status == '3'
										? { background: '#409EFF', color: '#FFF' }
										: { background: '#FFF', color: '#606266' }
								"
								size="mini"
								@click="handleQuickQuery('3')"
								>{{ '过号等候' }}
							</el-button>
							<el-button
								:style="
									status == '2'
										? { background: '#409EFF', color: '#FFF' }
										: { background: '#FFF', color: '#606266' }
								"
								size="mini"
								@click="handleQuickQuery('2')"
								>{{ '就诊中' }}
							</el-button>
							<el-button
								:style="
									status == '5'
										? { background: '#409EFF', color: '#FFF' }
										: { background: '#FFF', color: '#606266' }
								"
								size="mini"
								@click="handleQuickQuery('5')"
								>{{ '初诊完成' }}
							</el-button>
							<el-button
								:style="
									status == '8'
										? { background: '#409EFF', color: '#FFF' }
										: { background: '#FFF', color: '#606266' }
								"
								size="mini"
								@click="handleQuickQuery('8')"
								>{{ '复诊完成' }}
							</el-button>
							<el-button
								:style="
									status == '4'
										? { background: '#409EFF', color: '#FFF' }
										: { background: '#FFF', color: '#606266' }
								"
								size="mini"
								@click="handleQuickQuery('4')"
								>{{ '过号移出' }}
							</el-button>
							<el-button
								:style="
									status == '7'
										? { background: '#409EFF', color: '#FFF' }
										: { background: '#FFF', color: '#606266' }
								"
								size="mini"
								@click="handleQuickQuery('7')"
								>{{ '手动移出' }}
							</el-button>
						</el-group-button>
					</el-col>
					<div class="top-right-btn">
						<el-tooltip
							class="item"
							effect="dark"
							:content="$t('elButton.refresh')"
							placement="top"
						>
							<el-button
								size="mini"
								circle
								icon="el-icon-refresh"
								@click="handleQuery"
							/>
						</el-tooltip>
						<el-tooltip
							class="item"
							effect="dark"
							:content="
								showSearch
									? $t('elButton.hideSearch')
									: $t('elButton.showSearch')
							"
							placement="top"
						>
							<el-button
								size="mini"
								circle
								icon="el-icon-search"
								@click="showSearch = !showSearch"
							/>
						</el-tooltip>
					</div>
				</el-row>

				<el-table
					v-loading="loading"
					:data="queueInfoList"
					@selection-change="handleSelectionChange"
				>
					<el-table-column type="selection" width="55" align="center" />
					<!-- <el-table-column label="序号" type="index" width="50" /> -->
					<el-table-column
						:label="$t('calling.patientName')"
						align="center"
						prop="customerName"
					/>

					<el-table-column
						:label="$t('calling.docterName')"
						align="center"
						prop="staffName"
					/>
					<el-table-column
						:label="$t('program.status')"
						align="center"
						prop="status"
						:formatter="statusFormat"
					/>
					<el-table-column label="就诊时间" align="center" prop="callTime" />
					<el-table-column
						label="前面等待人数"
						align="center"
						prop="waitNum"
					/>

					<el-table-column
						:label="$t('calling.businessName')"
						align="center"
						prop="bizinfoName"
					/>
					<!-- <el-table-column :label="$t('calling.serial')" align="center" prop="sort" /> -->
          <!-- :formatter="isEmergencyFormat" -->
					<el-table-column
						:label="$t('calling.isEmergency')"
						align="center"
						prop="isEmergency "
						
					/>
					<el-table-column
						:label="$t('calling.isFirst')"
						align="center"
						prop="isPrior"
						:formatter="isPriorFormat"
					/>
					<el-table-column
						:label="$t('calling.ticketNumber')"
						align="center"
						prop="ticketNo"
					/>
          <el-table-column
						label="患者编号"
						align="center"
						prop="externalCustomerId"
					/>
					<el-table-column
						:label="$t('calling.windowName')"
						align="center"
						prop="counterName"
					/>
					<el-table-column
						:label="$t('calling.checkTime')"
						align="center"
						prop="reportTime"
						width="180"
					>
						<template slot-scope="scope">
							<span>{{ parseTime(scope.row.reportTime) }}</span>
						</template>
					</el-table-column>
					<el-table-column
						label="等待时长"
						align="center"
						prop="waitTime"
						width="180"
					>
					</el-table-column>
					<el-table-column
						:label="$t('calling.completionTime')"
						align="center"
						prop="completeTime"
						width="170"
					>
						<template slot-scope="scope">
							<span>{{ parseTime(scope.row.completeTime) }}</span>
						</template>
					</el-table-column>

					<el-table-column
						:label="$t('elButton.establishTime')"
						align="center"
						prop="createTime"
						width="180"
					>
						<template slot-scope="scope">
							<span>{{ parseTime(scope.row.createTime) }}</span>
						</template>
					</el-table-column>
					<el-table-column
						:label="$t('equipment.control')"
						align="center"
						width="200px"
						class-name="small-padding fixed-width"
						fixed="right"
					>
						<template slot-scope="scope">
							<el-button
								size="medium"
								type="text"
								icon="el-icon-edit"
								@click="referral(scope.row)"
							/>
							<el-button
								size="medium"
								type="text"
								icon="el-icon-close"
								@click="abandoned(scope.row)"
							/>
							<!-- <el-button
								size="medium"
								type="text"
								icon="el-icon-top"
								@click="moveQueue(scope.row, 1)"
							/>
							<el-button
								size="medium"
								type="text"
								icon="el-icon-bottom"
								@click="moveQueue(scope.row, 2)"
							/> -->
							<el-button
								size="medium"
								type="text"
								icon="el-icon-sort"
								@click="openQueue(scope.row)"
							/>
							<el-button
								size="medium"
								type="text"
								icon="el-icon-refresh-right"
								@click="relisting(scope.row)"
							/>
						</template>
					</el-table-column>
				</el-table>

				<pagination
					v-show="total > 0"
					:total="total"
					:page.sync="queryParams.current"
					:limit.sync="queryParams.size"
					@pagination="getList"
				/>
			</el-col>
		</el-row>
		<!-- 添加或修改队列信息对话框 -->
		<el-dialog
			:title="title"
			:visible.sync="open"
			:modal-append-to-body="true"
			:append-to-body="true"
			:close-on-click-modal="false"
			style="overflow:auto"
		>
			<el-tabs v-model="activeName" @tab-click="handleClick">
				<el-tab-pane label="普通登记" name="first">
					<el-form ref="form" :model="form" :rules="rules" label-width="80px">
						<el-row :gutter="20">
							<el-col :span="11">
								<el-form-item :label="$t('calling.business')" prop="bizinfoId">
									<el-select filterable  v-model="form.bizinfoId" @change="bizinfoChange()">
										<el-option
											v-for="bizinfo in isHandwork
												? detailBizinfoOptionss
												: bizinfoOptionss"
											:key="bizinfo.id"
											:value="bizinfo.id"
											:label="bizinfo.name"
										/>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="11">
								<el-form-item :label="$t('calling.window')" prop="counterId">
									<el-select filterable v-model="form.counterId" @change="counterChange()">
										<el-option
											v-for="counter in counterOptions"
											:key="counter.id"
											:value="counter.id"
											:label="counter.name"
										/>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col
								v-if="showCase === 'add' || showCase === 'report'"
								:span="11"
							>
								<el-form-item :label="$t('calling.report')">
									<el-radio-group v-model="form.status">
										<el-radio label="1">{{
											$t('calling.reportRightnow')
										}}</el-radio>
										<!-- <el-radio label="0">{{ $t('calling.reportWait') }}</el-radio> -->
									</el-radio-group>
								</el-form-item>
							</el-col>
							<el-col :span="11">
								<el-form-item :label="$t('calling.isEmergency')">
										<el-switch
											v-model="form.isEmergency"
											active-color="#13ce66"
											inactive-color="#ff4949"
                      active-value='1'
                      inactive-value='0'
										>
										</el-switch>
								</el-form-item>
							</el-col>
              	<el-col :span="11">
								<el-form-item :label="$t('calling.statusSelect')">
										<el-select v-model="form.status">
										<el-option
											v-for="item in waitStatusOptions"
											:key="item.id"
											:value="item.value"
											:label="item.label"
										/>
									</el-select>
								</el-form-item>
							</el-col>
							<!-- v-if="showCase === 'add'"  -->
							<el-col :span="22">
								<el-row :gutter="20">
									<el-col :span="22">
										<el-divider content-position="left">{{
											$t('calling.patientInfo')
										}}</el-divider>
									</el-col>
									<el-col :span="11">
										<el-form-item
											:label="$t('calling.peopleName')"
											prop="customerName"
										>
											<!-- <el-input
												v-model="form.customerName"
												:placeholder="$t('calling.peopleNameInput')"
											/> -->
											<el-autocomplete
												class="inline-input"
												v-model="form.customerName"
												:fetch-suggestions="querySearch"
												placeholder="请输入内容"
												@select="handleSelect"
											>
												<template slot-scope="{ item }">
													<div
														v-infinite-scroll="scrollLoad"
														class="infinite-list"
													>
														{{ `${item.cnName}(${item.cardNo})` }}
													</div>
												</template>
											</el-autocomplete>
										</el-form-item>
									</el-col>
									<el-col :span="11">
										<el-form-item :label="$t('calling.enName')" prop="enName">
											<el-input
												v-model="form.customerEnName"
												:placeholder="$t('calling.enNameInput')"
											/>
										</el-form-item>
									</el-col>
									<el-col :span="11">
										<el-form-item :label="$t('calling.age')" prop="age">
											<el-input-number
												v-model="form.customerAge"
												controls-position="right"
												:min="0"
											/>
										</el-form-item>
									</el-col>
									<el-col :span="11">
										<el-form-item :label="$t('calling.sex')">
											<el-select
												v-model="form.customerSex"
												:placeholder="$t('calling.sexSelect')"
											>
												<el-option
													key="0"
													:label="$t('calling.boy')"
													value="0"
												/>
												<el-option
													key="1"
													:label="$t('calling.girl')"
													value="1"
												/>
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="11">
										<el-form-item :label="$t('calling.nation')" prop="nation">
											<el-input
												v-model="form.customerNation"
												:placeholder="$t('calling.nationInput')"
											/>
										</el-form-item>
									</el-col>
									<el-col :span="11">
										<el-form-item
											:label="$t('calling.cardNo')"
											prop="customerCardNo"
										>
											<el-input
												v-model="form.customerCardNo"
												:placeholder="$t('calling.cardNoInput')"
											/>
										</el-form-item>
									</el-col>
									<el-col :span="11">
										<el-form-item :label="$t('calling.address')" prop="address">
											<el-input
												v-model="form.customerAddress"
												:placeholder="$t('calling.addressInput')"
											/>
										</el-form-item>
									</el-col>
									<el-col :span="11">
										<el-form-item :label="$t('calling.phone')" prop="telphone">
											<el-input
												v-model="form.customerTelphone"
												:placeholder="$t('calling.phoneInput')"
											/>
										</el-form-item>
									</el-col>
									<el-col :span="22">
										<el-form-item
											:label="$t('calling.synopsis')"
											prop="introduce"
										>
											<el-input
												v-model="form.customerIntroduce"
												type="textarea"
												:placeholder="$t('calling.synopsisInput')"
											/>
										</el-form-item>
									</el-col>
								</el-row>
							</el-col>
						</el-row>
					</el-form>
				</el-tab-pane>
				<el-tab-pane label="绿色通道" name="second">
					<el-form
						ref="from"
						:model="form"
						:rules="rules"
						label-width="80px"
						:inline="true"
					>
						<!-- 姓名 -->
						<el-form-item
							:label="$t('calling.peopleName')"
							prop="name"
							style="width:50%"
						>
							<el-input
								v-model="form.name"
								:placeholder="$t('calling.peopleNameInput')"
							/>
						</el-form-item>
						<!-- 证件号码 -->
						<el-form-item :label="$t('calling.cardNo')" prop="cardNo">
							<el-input
								v-model="form.cardNo"
								:placeholder="$t('calling.cardNoInput')"
							/>
						</el-form-item>
						<!-- 业务 -->
						<el-form-item
							:label="$t('calling.business')"
							prop="bizinfoId"
							style="width:50%"
						>
							<el-select v-model="form.bizinfoId" @change="bizinfoChange()">
								<el-option
									v-for="bizinfo in bizinfoOptionss"
									:key="bizinfo.id"
									:value="bizinfo.id"
									:label="bizinfo.name"
								/>
							</el-select>
						</el-form-item>
						<!-- 窗口 -->
						<el-form-item :label="$t('calling.window')" prop="counterId">
							<el-select v-model="form.counterId" @change="counterChange()">
								<el-option
									v-for="counter in counterOptions.filter(
										(item) => item.status == '0'
									)"
									:key="counter.id"
									:value="counter.id"
									:label="counter.name"
								/>
							</el-select>
						</el-form-item>
						<el-form-item
							label="插入队列位置"
							label-width="110"
							style="width:100%"
							prop="sort"
						>
							<el-input-number v-model="form.sort" :min="1"></el-input-number>
						</el-form-item>
						<el-form-item :label="$t('calling.report')">
							<el-radio-group v-model="form.status">
								<el-radio label="1">{{
									$t('calling.reportRightnow')
								}}</el-radio>
								<!-- <el-radio label="0">{{ $t('calling.reportWait') }}</el-radio> -->
							</el-radio-group>
						</el-form-item>
					</el-form>
				</el-tab-pane>
			</el-tabs>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">{{
					$t('submitText')
				}}</el-button>
				<el-button @click="cancel">{{ $t('cancelText') }}</el-button>
			</div>
		</el-dialog>
		<el-dialog
			title="语音播报叫号"
			:visible.sync="callNumDialog"
			:modal-append-to-body="true"
			:append-to-body="true"
			:close-on-click-modal="false"
		>
			语音播报内容: <el-input v-model="speechValue"></el-input>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="speechContent">{{
					$t('submitText')
				}}</el-button>
				<el-button @click="() => (callNumDialog = false)">{{
					$t('cancelText')
				}}</el-button>
			</div>
		</el-dialog>
		<el-dialog
			title="语音播报"
			:visible.sync="voiceAnnouncementsDialog"
			:modal-append-to-body="true"
			:append-to-body="true"
			:close-on-click-modal="false"
			width="35%"
		>
			<el-form :model="voiceAnnouncements" label-width="100px" :inline="true">
				<el-form-item label="播报内容：" prop="speechTargetValue">
					<el-input v-model="speechTargetValue"></el-input>
				</el-form-item>
				<el-form-item label="播报目标：" prop="speechTarget">
					<el-select
						v-model="speechTarget.target"
						multiple
						ref="selectRef"
						@remove-tag="removeTag"
						@visible-change="selectRefVisible"
						@focus="focusTrees(true)"
					>
						<!-- <template slot-scope="{ item }">
							{{ item }}
						</template> -->
					</el-select>
					<el-tree
						v-show="focusTreesData == true"
						ref="tree"
						:data="bizinfoOptions"
						:props="defaultProps"
						:expand-on-click-node="false"
						:filter-node-method="filterNode"
						:highlight-current="true"
						@node-click="handleDialogNodeClick"
					>
						<span class="custom-tree-node" slot-scope="{ node, data }">
							<span>{{ node.label }}</span>
						</span>
					</el-tree>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="speechTargetEvent">{{
					$t('submitText')
				}}</el-button>
				<el-button @click="() => (voiceAnnouncementsDialog = false)">{{
					$t('cancelText')
				}}</el-button>
			</div>
		</el-dialog>

		<el-dialog
			title="队列顺序调整"
			:visible.sync="queueSequencingDialog"
			:modal-append-to-body="true"
			:append-to-body="true"
			:close-on-click-modal="false"
			width="35%"
		>
			<el-form
				:model="queueSequencingValues"
				label-width="140px"
				:inline="true"
			>
				<el-form-item label="当前患者：" prop="currentPatient">
					{{ currentPatient }}
				</el-form-item>
				<el-form-item label="当前诊室：" prop="currentConsultation">
					{{ currentConsultation }}
				</el-form-item>
				<el-form-item label="移动至：" prop="movePosition">
					<el-select
						ref="moveSelect"
						v-model="movePosition"
						placeholder="请选择"
						class="infinite-list"
					>
						<el-option
							v-infinite-scroll="handleScroll"
							v-for="item in movePositionOptions"
							:key="item.id"
							:label="
								'位置' +
									item.indexId +
									'-' +
									item.customerName +
									'-' +
									item.ticketNo
							"
							:value="item.id"
						>
						</el-option>
					</el-select>
					<el-tooltip
						content="移动后原位置人员将依次后移"
						placement="top"
						effect="light"
					>
						<span
							style="
							margin-left: 20px;
							border-radius: 50%;
							color: #FFF;
							background: black;
							height: 20px;
							font-size: 15px;
							width: 20px;
							display: inline-block;
							text-align: center;
							line-height: 20px;"
						>
							？
						</span>
					</el-tooltip>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="queueSequencingEvent">{{
					$t('submitText')
				}}</el-button>
				<el-button @click="() => (queueSequencingDialog = false)">{{
					$t('cancelText')
				}}</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import {
	listQueueInfo,
	getQueueInfo,
	delQueueInfo,
	addQueueInfo,
	addGreenWay,
	editQueueInfo,
	clean,
	moveAppointment,
	exportQueueInfo,
	reportQueueInfo,
	priorQueueInfo,
	abandonedQueueInfo,
	replayQueueInfo,
	referralQueueInfo,
	relistingQueueInfo,
	moveQueueInfo,
	callSpeech,
	batchCallSpeech,
} from '@/api/qbs/queueInfo'
import { bizinfoTree, listBizinfo, listDetailBizinfo } from '@/api/qbs/bizinfo'
import { listCounter } from '@/api/qbs/counter'
import { listCustomer } from '@/api/qbs/customer'
import eventbus from '@/utils/eventbus'

export default {
	name: 'Triage',
	data() {
		return {
			// 展示信息
			showCase: 'add',
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 总条数
			total: 0,
			// 队列信息表格数据
			queueInfoList: [],
			pageSize: 10,
			// 弹出层标题
			title: '',
			// 是否显示弹出层
			open: false,
			name: undefined,
			bizinfoOptions: [],
			bizinfoOptionss: [],
			customerOptions: [],
			counterOptions: [],
			defaultProps: {
				children: 'counterList',
				label: (data, node) => {
					return data.name || data.counterName
				},
			},
			// 日期范围
			dateRange: [
				new Date().toLocaleDateString().replaceAll('/', '-'),
				new Date().toLocaleDateString().replaceAll('/', '-'),
			],
			// 是否优先字典
			isPriorOptions: [], // 状态字典
      waitStatusOptions:[],// 等待状态字典
			statusOptions: [], // 查询参数
			reportTime: '', // 筛选报到时间（控件绑定数据）
			queryParams: {
				current: 1,
				size: 10,
				ticketNo: undefined,
				counterName: undefined,
				bizinfoId: undefined,
				bizinfoName: undefined,
				isPrior: undefined,
				status: undefined,
				createTime: undefined,
				beginReportTime: undefined, // 报到时间开始
				endReportTime: undefined, // 报到时间结束
			},
			// 显示搜索条件
			showSearch: true,
			// 表单参数
			form: {},
			// 选中
			selection: {},
			// 语音播报弹框
			callNumDialog: false,
			activeName: 'first',
			voiceAnnouncementsDialog: false, // 语音播报窗体
			focusTreesData: false, // 当前下拉框已选树数据
			showDropdown: false, // 语音播报窗体下拉框
			// 表单校验
			rules: {
				cardNo: [
					{ required: true, message: '证件号码不能为空', trigger: 'blur' },
				],
				name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
				bizinfoId: [
					{ required: true, message: '业务不能为空', trigger: 'change' },
				],
				counterId: [
					{ required: true, message: '窗口不能为空', trigger: 'change' },
				],
				sort: [
					{
						required: true,
						message: '插入队列不能为空',
						trigger: 'change',
					},
				],
			},
			speechValue: '',
			speechTargetValue: '', // 语音播报窗体内容
			// 语音播报窗体目标
			speechTarget: {
				target: [],
				id: [],
			},
			// 重置队列按钮
			relistingAble: true,
			// 移出队列按钮
			abandonedAble: true,
			// 语音播报按钮
			voiceAnnouncementsAble: true,
			// 快速筛选按钮index
			status: '',
			queueSequencingDialog: false, // 队列顺序调整窗体
			queueSequencingValues: {},
			currentPatient: '', // 当前患者
			currentConsultation: '', // 当前诊室
			movePositionOptions: [], // 队列顺序调整可移动的数据
			movePosition: '', // 队列顺序调整已选移动数据
			currentPositionId: '', // 当前数据id
			currentCounterId: '', // 当前诊室id
			// 是否手工录入
			isHandwork: false,
			// 具体部门下的业务列表
			detailBizinfoOptionss: [],
			indexId: 0,
		}
	},
	watch: {
		open(value) {
			if (!value) {
				this.isHandwork = value
			}
		},
		// 根据名称筛选分类名称树
		name(val) {
			this.$refs.tree.filter(val)
		},
	},
	computed: {
		// 语音播报内容
		// speechValue() {
		// 	if (this.selection.length) {
		// 		return `请${this.selection[0].customerName}患者到分诊台处`
		// 	}
		// },
	},
	created() {
		this.getList()
		this.getBizinfoTree()
		this.getBizinfoList()
		this.getlistDetailBizinfo()
		this.getCustomerList()
		this.getDicts('yes_no').then((response) => {
			this.isPriorOptions = response.data
		})
		this.getDicts('queue_status').then((response) => {
			this.statusOptions = response.data
		})
    this.getDicts('queue_wait_status').then((response) => {
			this.waitStatusOptions = response.data
		})
	},
	mounted() {
		eventbus.$on('websocket', (data) => {
			console.log('websocket', data)
			if (data.type == '112' /*后端定义常量消息结构：网页刷新审核状态*/) {
				console.log('refreshrefresh::', data)
				this.getList()
			}
			if (data.type == 1) {
				let to_speak = new SpeechSynthesisUtterance(data.payload.data)
				window.speechSynthesis.speak(to_speak)
				this.$notify({
					title: '呼叫',
					message: data.payload.data,
				})
				// this.$message({
				// 	message: message.data,
				// })
			}
		})
		this.$once('hook:beforeDestroy', () => {
			eventbus.$off('websocket')
		})
	},
	methods: {
		// 按关键字搜索已存在患者
		querySearch(queryString, cb) {
			let customerOptions = this.customerOptions
			let result = []
			if (queryString.trim()) {
				for (let index in customerOptions) {
					if (customerOptions[index].cnName.includes(queryString)) {
						result.push(customerOptions[index])
					}
				}
			} else {
				result = customerOptions
			}
			cb(result)
		},
		// 选择并填入表单
		handleSelect(data) {
			this.form.customerName = data.cnName
			this.form.customerEnName = data.enName
			this.form.customerAge = data.age
			this.form.customerSex = data.sex
			this.form.customerCardNo = data.cardNo
			this.form.customerAddress = data.address
			this.form.customerTelphone = data.telphone
			this.form.customerIntroduce = data.introduce
		},
		/** 查询队列信息列表 */
		getList() {
			this.loading = true
			listQueueInfo(this.queryParams).then((response) => {
				this.queueInfoList = response.data.map((obj, index) => {
					obj.indexId = index + 1
					return obj
				})
				this.total = response.total
				this.loading = false
			})
		},
		getDialogList(current, size, counterId) {
			listQueueInfo({ current, size, counterId }).then((response) => {
				let movePositionOptions = response.data
					.filter((item) => ['1', '3', '6'].includes(item.status))
					.map((obj, index) => ({ ...obj, indexId: this.indexId + index + 1 }))
					.filter((obj) => obj.id !== this.currentPositionId)
				this.movePositionOptions = this.movePositionOptions.concat(
					movePositionOptions
				)
				this.indexId = this.movePositionOptions[
					this.movePositionOptions.length - 1
				].indexId
			})
		},
		getBizinfoTree() {
			bizinfoTree().then((response) => {
				this.bizinfoOptions = response.data.filter((item) => {
					if (item.deptId) {
						return item
					}
				})
			})
		},
		loadChildrenNode(node, resolve) {
			if (!node.data.id) return
			listQueueInfo({ bizinfoId: node.data.id }).then((response) => {
				resolve(response.data)
			})
		},
		// 获取业务列表
		getBizinfoList() {
			listBizinfo({ current: 1, size: 1000 }).then((response) => {
				this.bizinfoOptionss = response.data.map((item) => {
					// item.id = item.id
					return item
				})
			})
		},
		// 获取具体部门下的业务列表
		getlistDetailBizinfo() {
			listDetailBizinfo({ current: 1, size: 1000 }).then((response) => {
				this.detailBizinfoOptionss = response.data.map((item) => {
					// item.id = item.id
					return item
				})
			})
		},
		// 获取诊室列表
		getCounterList(val) {
			listCounter({
				current: 1,
				size: 1000,
				bizinfoIds: this.form.bizinfoId,
				status: 0,
			}).then((response) => {
				this.counterOptions = response.data.map((item) => {
					// item.id = item.id
					return item
				})
			})
		},
		// 获取患者列表
		getCustomerList() {
			listCustomer({ current: 1, size: 1000 }).then((response) => {
				this.customerOptions = response.data.map((item) => {
					// item.id = item.id
					return item
				})
			})
		},
		// 门诊室赋名
		bizinfoChange() {
			if (this.form.bizinfoId) {
				this.bizinfoOptionss.map((item) => {
					if (this.form.bizinfoId === item.id) {
						this.form.bizinfoName = item.name
					}
				})
			} else {
				this.form.bizinfoName = ''
			}
			this.form.counterId = ''
			this.getCounterList()
		},
		// 业务赋名
		counterChange() {
			if (this.form.counterId) {
				this.counterOptions.map((item) => {
					if (this.form.counterId === item.id) {
						this.form.counterName = item.name
					}
				})
			} else {
				this.form.counterName = ''
			}
		},
		// 患者赋名
		customerChange() {
			if (this.form.customerId) {
				this.customerOptions.map((item) => {
					if (this.form.customerId === item.id) {
						this.form.customerName = item.cnName
					}
				})
			} else {
				this.form.customerName = ''
			}
		},
		// 筛选节点
		filterNode(value, data) {
			if (!value) return true
			return data.name.indexOf(value) !== -1
		},
		// 树节点单击事件
		async handleNodeClick(data) {
			this.queryParams = {
				current: 1,
				size: this.pageSize,
			}
			if (data.bizinfoIds) {
				this.queryParams.counterId = data.id
				this.queryParams.current = 1
				this.getList()
			} else {
				this.queryParams.bizinfoId = data.id === 0 ? undefined : data.id
				this.queryParams.current = 1
				this.getList()
			}
		},
		// 窗体树节点单击事件
		handleDialogNodeClick(data) {
			if (!data.counterList) {
				if (!this.speechTarget.id.includes(data.name + '(' + data.id + ')')) {
					this.speechTarget.target.push(data.name + '(' + data.id + ')')
					this.speechTarget.id.push(data.name + '(' + data.id + ')')
				} else {
					this.speechTarget.target = this.speechTarget.target.filter(
						(item) => item !== data.name + '(' + data.id + ')'
					)
					this.speechTarget.id = this.speechTarget.id.filter(
						(item) => item !== data.name + '(' + data.id + ')'
					)
				}
			} else if (data.counterList && data.counterList.length > 0) {
				for (let index in data.counterList) {
					if (
						!this.speechTarget.id.includes(
							data.counterList[index].name +
								'(' +
								data.counterList[index].id +
								')'
						)
					) {
						this.speechTarget.target.push(
							data.counterList[index].name +
								'(' +
								data.counterList[index].id +
								')'
						)
						this.speechTarget.id.push(
							data.counterList[index].name +
								'(' +
								data.counterList[index].id +
								')'
						)
					} else {
						this.speechTarget.target = this.speechTarget.target.filter(
							(item) =>
								item !==
								data.counterList[index].name +
									'(' +
									data.counterList[index].id +
									')'
						)
						this.speechTarget.id = this.speechTarget.id.filter(
							(item) =>
								item !==
								data.counterList[index].name +
									'(' +
									data.counterList[index].id +
									')'
						)
					}
				}
			}
		},
		// 移除播放目标
		removeTag(data) {
			for (let key in this.speechTarget.id) {
				if (this.speechTarget.id[key] == data) {
					delete this.speechTarget.id[key]
				}
			}
		},
		normalizer(node) {
			if (node.children && !node.children.length) {
				delete node.children
			}
			return {
				id: node.id,
				label: node.name,
				children: node.children,
			}
		},
		// 是否优先字典翻译
		isPriorFormat(row, column) {
			return this.selectDictLabel(this.isPriorOptions, row.isPrior)
		},
		// 状态字典翻译
		statusFormat(row, column) {
			return this.selectDictLabel(this.statusOptions, row.status)
		},
    // 等待状态字典翻译
    isEmergencyFormat(row, column) {
			return this.selectDictLabel(this.waitStatusOptions, row.status)
		},
		// 取消按钮
		cancel() {
			this.open = false
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				id: undefined,
				ticketNo: undefined,
				counterId: undefined,
				counterName: undefined,
				bizinfoId: undefined,
				bizinfoName: undefined,
				deptId: undefined,
				staffId: undefined,
				staffName: undefined,
				customerId: undefined,
				customerName: '',
				customerEnName: undefined,
				customerAge: 0,
				customerSex: '0',
				customerNation: '汉族',
				customerCardNo: undefined,
				customerAddress: undefined,
				customerTelphone: undefined,
				customerIntroduce: undefined,
				sort: 1,
				isPrior: '1',
				reportTime: undefined,
				startTime: undefined,
				completeTime: undefined,
				oldCounterId: undefined,
				status: '1',
			}
			this.resetForm('form')
		},
		// 报到时间
		changeReportTime(data) {
			if (data) {
				this.queryParams.beginReportTime = data[0]
					.toLocaleString()
					.replace(/\//g, '-')
				this.queryParams.endReportTime = data[1]
					.toLocaleString()
					.replace(/\//g, '-')
			} else {
				this.queryParams.beginReportTime = ''
				this.queryParams.endReportTime = ''
			}
		},
		/** 刷新按钮操作 */
		handleQuery(status) {
			this.queryParams.current = 1
			this.getList()
			// 刷新树
			this.getBizinfoTree()
		},
		handleQuickQuery(status) {
			if (status == this.status) {
				this.status = undefined
				this.queryParams.status = undefined
			} else {
				this.status = status
				this.queryParams.current = 1
				if (status) {
					this.queryParams.status = status
				} else {
					this.queryParams.status = undefined
				}
			}
			this.getList()
		},
		/** 重置按钮操作 */
		resetQuery() {
			// this.dateRange = []
			// this.resetForm('queryForm')
			this.status = ''
			this.queryParams = {}
			this.reportTime = ''
			this.handleQuery()
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.selection = selection
			this.ids = selection.map((item) => item.id)
			this.single = selection.length !== 1
			this.multiple = !selection.length
			// 重置按钮和移出队列按钮要根据病人状态来显示
			if (!this.single) {
				this.statusOptions.forEach((item) => {
					if (item.value == this.selection[0].status) {
						this.relistingAble = [
							'初诊等候',
							'复诊等候',
							'过号等候',
							'就诊中',
						].includes(item.label)
					}
				})
				this.abandonedAble = !this.relistingAble
			}
		},

		/** 新增按钮操作 */
		handleAdd() {
			this.isHandwork = true
			this.reset()
			this.open = true
			this.title = this.$t('elButton.importByhand')
			this.showCase = 'add'
			this.counterOptions = []
		},
		/** 修改按钮操作 */
		handleEdit(row) {
			this.reset()
			this.showCase = 'edit'
			const id = row.id || this.ids
			getQueueInfo(id).then((response) => {
				this.form = response.data
				this.open = true
				this.title = this.$t('calling.changeQueueInfo')
			})
		},
		/** 提交按钮 */
		submitForm: function() {
			this.$refs['form'].validate((valid) => {
				console.log('object', this.showCase, valid)
				console.log('form', this.form)
				if (valid) {
					if (this.form.id !== undefined) {
						switch (this.showCase) {
							case 'edit':
								editQueueInfo(this.form).then((response) => {
									if (response.code === 0) {
										this.msgSuccess(this.$t('loginLog.changeSuccess'))
										this.open = false
										this.getList()
									} else {
										this.msgError(response.msg)
									}
								})
								break
							case 'report':
								reportQueueInfo(this.form).then((response) => {
									if (response.code === 0) {
										this.msgSuccess(this.$t('calling.checkSuccess'))
										this.open = false
										this.getList()
									} else {
										this.msgError(response.msg)
									}
								})
								break
							case 'referral':
								referralQueueInfo(this.form).then((response) => {
									if (response.code === 0) {
										this.msgSuccess(this.$t('calling.referralSuccess'))
										this.open = false
										this.getList()
									} else {
										this.msgError(response.msg)
									}
								})
								break
						}
						// if (this.showCase === 'edit') {

						// }
					} else {
						if (this.activeName === 'first') {
							addQueueInfo(this.form).then((response) => {
								if (response.code === 0) {
									this.msgSuccess(this.$t('addSuccess'))
									this.open = false
									this.getList()
								} else {
									this.msgError(response.msg)
								}
							})
						} else {
							console.log(`<<<<2023年03月24日 15:00:16>>>>`, {
								'this.form': this.form,
							})
							addGreenWay(this.form).then((response) => {
								if (response.code === 0) {
									this.msgSuccess(this.$t('addSuccess'))
									this.open = false
									this.getList()
								} else {
									this.msgError(response.msg)
								}
							})
						}
					}
				}
			})
		},
		/** 删除按钮操作 */
		handleDel(row) {
			const ids = row.id || this.ids
			this.$confirm(
				this.$t('calling.enterDeleteQueueInfo') +
					ids +
					this.$t('equipment.deleteEquipment2'),
				this.$t('warning'),
				{
					confirmButtonText: this.$t('submitText'),
					cancelButtonText: this.$t('cancelText'),
					type: 'warning',
				}
			)
				.then(function() {
					return delQueueInfo(ids)
				})
				.then(() => {
					this.getList()
					this.msgSuccess(this.$t('deleteSuccess'))
				})
				.catch(function() {})
		},
		// 优先
		prior(row) {
			const id = row.id || this.ids
			this.$confirm(this.$t('calling.advanceQueueInfo'), this.$t('info'), {
				confirmButtonText: this.$t('submitText'),
				cancelButtonText: this.$t('cancelText'),
				type: 'info',
			})
				.then(function() {
					return priorQueueInfo(id)
				})
				.then(() => {
					this.getList()
					this.msgSuccess(this.$t('settingSuccess'))
				})
				.catch(function() {})
		},
		// 报到
		report(row) {
			this.reset()
			this.showCase = 'report'
			const id = row.id || this.ids
			getQueueInfo(id).then((response) => {
				this.form = response.data
				this.form.status = '1'
				this.open = true
				this.title = this.$t('calling.reportQueueInfo')
				this.getCounterList()
			})
		},
		// 转诊
		referral(row) {
			this.reset()
			this.showCase = 'referral'
			const id = row.id || this.ids
			getQueueInfo(id).then((response) => {
				this.form = response.data
				this.form.oldCounterId = this.form.counterId
				this.open = true
				this.title = this.$t('calling.reportQueueInfo')
				this.getCounterList()
			})
		},
		/** 弃号 */
		abandoned(row) {
			const id = row.id || this.ids
			this.$confirm(this.$t('calling.greenQueueInfo'), this.$t('warning'), {
				confirmButtonText: this.$t('submitText'),
				cancelButtonText: this.$t('cancelText'),
				type: 'warning',
			})
				.then(function() {
					return abandonedQueueInfo(id)
				})
				.then(() => {
					this.getList()
					this.msgSuccess(this.$t('settingSuccess'))
				})
				.catch(function() {})
		},
		/** 复诊 */
		replay(row) {
			const id = row.id
			this.$confirm(
				this.$t('calling.replayEnter'),
				this.$t('calling.chatInfo'),
				{
					confirmButtonText: this.$t('submitText'),
					cancelButtonText: this.$t('cancelText'),
					type: 'info',
				}
			)
				.then(function() {
					return replayQueueInfo(id)
				})
				.then(() => {
					this.getList()
					this.msgSuccess(this.$t('calling.replaySuccess'))
				})
				.catch(function() {})
		},
		// 重新入列
		relisting(row) {
			this.reset()
			this.showCase = 'relisting'
			const id = row.id || this.ids
			relistingQueueInfo(id).then((response) => {
				this.$message({
					type: 'success',
					message: '重置成功',
				})
				this.getCounterList()
			})
		},
		// 移动队列
		moveQueue(row, moveType) {
			const id = row.id || this.ids
			moveQueueInfo({ id, moveType }).then((response) => {
				this.$message({
					type: 'success',
					message: '移动成功',
				})
			})
			// 刷新列表
			this.handleQuery()
		},
		// 打开移动队列（新
		openQueue(data) {
			if (!(data.status == '1' || data.status == '3' || data.status == '6')) {
				return this.$message({
					type: 'warning',
					message: '该患者不在等候队列中！',
				})
			}
			this.currentPositionId = data.id
			this.queueSequencingDialog = true
			// 每次打开重置
			this.queryParams.current = 1
			this.indexId = 0
			this.movePositionOptions = []
			this.movePosition = ''
			this.currentPatient =
				'位置' + data.indexId + '-' + data.customerName + '-' + data.ticketNo
			this.currentConsultation = data.counterName
			// 获取对应诊室资源
			this.currentCounterId = data.counterId
			this.getDialogList(
				this.queryParams.current,
				this.queryParams.size,
				data.counterId
			)
		},
		queueSequencingEvent() {
			const id = this.currentPositionId
			const moveType = 3
			const targetQueueId = this.movePosition
			moveQueueInfo({ id, moveType, targetQueueId }).then((response) => {
				this.$message({
					type: 'success',
					message: '移动成功',
				})
			})
			this.queueSequencingDialog = false
			// 刷新列表
			setTimeout(() => {
				this.handleQuery()
			}, 500)
		},
		// 队列顺序调整窗体下拉框滚动更新
		handleScroll() {
			var that = this
			// 获取当前高度差
			let scrollbarComponent = this.$refs.moveSelect.$children[1].$children[0]
			let max =
				scrollbarComponent.wrap.scrollHeight -
				scrollbarComponent.wrap.clientHeight
			let scrollInstance
			scrollbarComponent.wrap.onscroll = async (e) => {
				// 滚动的距离
				scrollInstance = e.target.scrollTop
				// 滚动到底部时，加载更多数据
				if (scrollInstance === max) {
					that.queryParams.current = that.queryParams.current + 1
					that.getDialogList(
						that.queryParams.current,
						that.queryParams.size,
						that.currentCounterId
					)
				}
			}
		},
		// 叫号
		callNum(row) {
			const id = row.id || this.ids
			this.callNumDialog = true
		},
		// 语音播报
		voiceAnnouncements() {
			this.voiceAnnouncementsDialog = true
			// 清空
			this.speechTargetValue = ''
			this.speechTarget = {
				target: [],
				id: [],
			}
		},
		// 触发下拉框变化时隐藏下拉框
		selectRefVisible() {
			this.$refs.selectRef.visible = false
		},
		// 聚焦开启树
		focusTrees(data) {
			this.focusTreesData = data
		},
		// 语音播报
		async speechContent() {
			this.callNumDialog = false
			await callSpeech({
				text: this.speechValue,
				counterId: this.selection[0].counterId,
			})
			let to_speak = new SpeechSynthesisUtterance(this.speechValue)
			window.speechSynthesis.speak(to_speak)

			this.$message({
				message: this.speechValue,
				center: true,
			})
		},
		// 语音播报
		async speechTargetEvent() {
			let counterIdArray = this.speechTarget.id.map((item) =>
				Number(item.replace(/.*\((.*)\)/, '$1'))
			)
			await batchCallSpeech({
				text: this.speechTargetValue,
				counterIdArray: counterIdArray,
			})
			let to_speak = new SpeechSynthesisUtterance(this.speechTargetValue)
			window.speechSynthesis.speak(to_speak)

			this.$message({
				message: this.speechTargetValue,
				center: true,
			})
			this.voiceAnnouncementsDialog = false
		},
		/** 导出按钮操作 */
		handleExport() {
			if (this.ids.length === 0) {
				this.msgWarning(this.$t('equipment.equipmentInput'))
				return
			}
			const queryParams = this.queryParams
			this.$confirm(
				this.$t('calling.enterExportQueueInfo'),
				this.$t('warning'),
				{
					confirmButtonText: this.$t('submitText'),
					cancelButtonText: this.$t('cancelText'),
					type: 'warning',
				}
			)
				.then(() => {
					return exportQueueInfo(queryParams, this.ids)
				})
				.then((response) => {
					this.download(response.data)
				})
				.catch(function() {})
		},
		/** 清空按钮操作 */
		handleClean(row) {
			const id = row.id || this.ids
			if (!id) {
				this.msgWarning(this.$t('equipment.equipmentInput'))
				return
			}
			const queryParams = this.queryParams
			this.$confirm(
				this.$t('calling.enterCleanQueueInfo'),
				this.$t('warning'),
				{
					confirmButtonText: this.$t('submitText'),
					cancelButtonText: this.$t('cancelText'),
					type: 'warning',
				}
			)
				.then(() => {
					return clean(id)
				})
				.then((response) => {
					this.getList()
				})
				.catch(function() {})
		},
		/** 移至预约按钮操作 */
		handlemoveAppointment() {
			if (this.ids.length === 0) {
				this.msgWarning(this.$t('equipment.equipmentInput'))
				return
			}
			const queryParams = this.queryParams
			this.$confirm(this.$t('calling.enterMoveQueueInfo'), this.$t('warning'), {
				confirmButtonText: this.$t('submitText'),
				cancelButtonText: this.$t('cancelText'),
				type: 'warning',
			})
				.then(() => {
					return moveAppointment(this.ids)
				})
				.then((response) => {
					this.getList()
				})
				.catch(function() {})
		},
	},
}
</script>
<style scoped>
.custom-tree-node {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: 14px;
	padding-right: 8px;
}
</style>
